<?php
/**
 * Created by PhpStorm.
 * User: HM22
 * Date: 2019/3/26
 * Time: 19:19
 */

namespace Alipay;


class AlipayService
{
    protected $appId;
    //私钥值
    protected $rsaPrivateKey;
    public function __construct($appid, $saPrivateKey, $signType)
    {
        $this->appId = $appid;
        $this->charset = 'utf8';
        $this->rsaPrivateKey=$saPrivateKey;
        $this->signType = $signType;
    }
    /**
     * 转帐
     * @param float $totalFee 转账金额，单位：元。
     * @param string $outTradeNo 商户转账唯一订单号
     * @param string $remark 转帐备注
     * @return array
     */
    public function doPay($totalFee, $outTradeNo, $account,$realName, $payer_show_name, $remark='')
    {
        //请求参数
        $requestConfigs = array(
            'out_biz_no'=>$outTradeNo,
            'payee_type'=>'ALIPAY_LOGONID',
            'payee_account'=>$account,
            'payee_real_name'=>$realName,  //收款方真实姓名
            'amount'=>$totalFee, //转账金额，单位：元。
            'payer_show_name' => $payer_show_name,
            'remark'=>$remark,  //转账备注（选填）
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appId,
            'method' => 'alipay.fund.trans.toaccount.transfer',             //接口名称
            'format' => 'JSON',
            'charset'=>$this->charset,
            'sign_type'=>$this->signType,
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);

//        $result = $this->curlPost('https://openapi.alipaydev.com/gateway.do',$commonConfigs); // 网关地址【沙箱环境】
        $result = $this->curlPost('https://openapi.alipay.com/gateway.do',$commonConfigs); //正式
        return json_decode($result,true);
    }


    /**
     * 转帐查询
     * @param string $outBizBo 商户转账唯一订单号（商户转账唯一订单号、支付宝转账单据号 至少填一个）
     * @param string $orderId 支付宝转账单据号（商户转账唯一订单号、支付宝转账单据号 至少填一个）
     * @return array
     */
    public function doQuery($outBizBo='',$orderId='')
    {
        //请求参数
        $requestConfigs = array(
            'out_biz_no'=>$outBizBo,
            'order_id'=>$orderId,
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appId,
            'method' => 'alipay.fund.trans.order.query',             //接口名称
            'format' => 'JSON',
            'charset'=>$this->charset,
            'sign_type'=>$this->signType,
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
//        $result = $this->curlPost('https://openapi.alipaydev.com/gateway.do',$commonConfigs); // 网关地址【沙箱环境】
        $result = $this->curlPost('https://openapi.alipay.com/gateway.do',$commonConfigs);
        return json_decode($result,true);



//        $aop = new AopClient();
//        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
//        $aop->appId = $this->appId;
//        $aop->rsaPrivateKey = 'MIIEpAIBAAKCAQEArUfFDtz7sE2nwnYTn4i8YTIseXM5lmoqQCMwo5FyMmlbDrFPsaFGhZH/f//o33PUZ4FoFBugYL+Tiop2mkK3t0XVxfSo3SjHjdk7uNcyBTHJLd9oEiRNV4V74iZhCkjSj9BmpZzVNrU4djZ6pRlK2arqAPwt9p7Tyd22iBS9i5WRRdJTnyz2YPh6POPXspae1YIsZn7uAOxt9o9kzD2P9wbkZJT3xLBG3zmZR5kO3Lh4aEymCC9QlOG6QeUMQWym1A3Op0elobGN4oj/ZKAgNLOnt6yWK9DzzFYXx4ZwCVEqCO/SeqCVsbnQy/AeQnTlSbhI6vADTAwwVZ8udtsjkQIDAQABAoIBAGx9KtuLb+mKNSaDVvXjXk5cY4wGoF+USK+vWJyQS7dUTzZ7vTGxj73BEv7I8rw0gR/s3YT5Zwgr6ewrlOYwL2YHyzgNXkxZY9dj0wh/c0ndSd/2p+nz4JiTcmS9MrSFs49nI109PCDshVU99ru3gi2V3LyRJxXpiyAwOEAq/CGPkvMxaysX5wo35GQVfGHvRb2Zi9Um3JxHKHgHhRjbXHmu7HfeV0mi3MzIr/aPXE/SjgzZFRKqj7OKkOfi4nud1cEEiclpTOGQ12JiDCTHNsf/y3+P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+Tiop2mkK3t0XVxfSo3SjHjdk7uNcyBTHJLd9oEiRNV4V74iZhCkjSj9BmpZzVNrU4djZ6pRlK2arqAPwt9p7Tyd22iBS9i5WRRdJTnyz2YPh6POPXspae1YIsZn7uAOxt9o9kzD2P9wbkZJT3xLBG3zmZR5kO3Lh4aEymCC9QlOG6QeUMQWym1A3Op0elobGN4oj/ZKAgNLOnt6yWK9DzzFYXx4ZwCVEqCO/SeqCVsbnQy/AeQnTlSbhI6vADTAwwVZ8udtsjkQIDAQAB';
//        $aop->apiVersion = '1.0';
//        $aop->signType = 'RSA2';
//        $aop->postCharset='UTF-8';
//        $aop->format='json';
//        $request = new AlipayFundTransOrderQueryRequest();
//        $request->setBizContent("{" .
//            "\"out_biz_no\":\"WD201904031705546896\"," .
////            "\"order_id\":\"20160627110070001502260006780837\"" .
//            "  }");
//        $result = $aop->execute($request);
//
//        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
//        $resultCode = $responseNode->code;
//
////        if(!empty($resultCode)&&$resultCode == 10000){
////            echo "成功";
////        } else {
////            echo "失败";
////        }
    }



    public function generateSign($params, $signType = "RSA") {
        return $this->sign($this->getSignContent($params), $signType);
    }
    protected function sign($data, $signType = "RSA") {
        $priKey=$this->rsaPrivateKey;
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');
        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
        } else {
            openssl_sign($data, $sign, $res);
        }
        $sign = base64_encode($sign);
        return $sign;
    }
    /**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     **/
    protected function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
        return false;
    }
    public function getSignContent($params) {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->charset);
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }
    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = $this->charset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }
        return $data;
    }
    public function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1000); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        //解决 中文乱码问题
        if(! mb_check_encoding($data, 'utf-8')) {
            $data = mb_convert_encoding($data,'UTF-8',['ASCII','UTF-8','GB2312','GBK']);
        }
        curl_close($ch);
        return $data;
    }
}